package k8s_ui

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/wonderivan/logger"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
)

var K8s_service k8s_service

type k8s_service struct{}

// 定义ServiceCreate结构体，用于创建service需要的参数属性的定义
type ServiceCreate struct {
	Name          string            `json:"name"`
	Namespace     string            `json:"namespace"`
	Type          string            `json:"type"`
	ContainerPort int32             `json:"container_port"`
	Port          int32             `json:"port"`
	NodePort      int32             `json:"node_port"`
	Label         map[string]string `json:"label"`
}

// 定义ServiceNp类型，用于返回namespace中Service的数量
type K8s_serviceNp struct {
	Namespace string `json:"k8s_servicename"`
	DaemonNum int    `json:"k8s_service_num"`
}

type K8s_serviceResp struct {
	Items []corev1.Service `json:"items"`
	Total int              `json:"total"`
}

func (p *k8s_service) GetServices(filterName, namespace string, limit, page int) (servicesResp *K8s_serviceResp, err error) {
	//获取ServiceList类型的service列表
	k8s_serviceSetList, err :=
		K8s.ClientSet.CoreV1().Services(namespace).List(context.TODO(),
			metav1.ListOptions{})
	if err != nil {
		logger.Error(errors.New("获取Service列表失败, " + err.Error()))
		return nil, errors.New("获取Service列表失败, " + err.Error())
	}

	//将ServiceList中的Service列表(Items)，放进dataselector对象中，进行排序
	selectableData := &DataSelector{
		GenericDataList: p.toCells(k8s_serviceSetList.Items),
		DataSelect: &DataSelectQuery{
			Filter: &FilterQuery{Name: filterName},
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	data := filtered.Sort().Paginate()
	//将[]DataCell类型的service列表转为service列表
	services := p.fromCells(data.GenericDataList)
	return &K8s_serviceResp{
		Items: services,
		Total: total,
	}, nil
}

// toCells方法用于将pod类型转成DataCell类型
func (*k8s_service) toCells(std []corev1.Service) []DataCell {
	cells := make([]DataCell, len(std))
	for i := range std {
		//std[i]原生pod类型 -> podCell -> DataCell
		cells[i] = k8s_serviceCell(std[i])
	}
	return cells
}

// fromCells方法用于将DataCell类型转成pod类型
func (*k8s_service) fromCells(cells []DataCell) []corev1.Service {
	services := make([]corev1.Service, len(cells))
	for i := range cells {
		//cells[i] DataCell接口类型 -> podCell -> 原生pod类型
		services[i] = corev1.Service(cells[i].(k8s_serviceCell))
	}
	return services
}

// 获取service详情
func (d *k8s_service) GetServiceDetail(serviceName, namespace string) (service *corev1.Service, err error) {
	service, err =
		K8s.ClientSet.CoreV1().Services(namespace).Get(context.TODO(), serviceName,
			metav1.GetOptions{})
	if err != nil {
		logger.Error(errors.New("获取service详情失败, " + err.Error()))
		return nil, errors.New("获取service详情失败, " + err.Error())
	}
	return service, nil
}

// 创建service,,接收ServiceCreate对象
func (d *k8s_service) CreateService(data *ServiceCreate) (err error) {
	//将data中的数据组装成corev1.Service对象
	service := &corev1.Service{
		//ObjectMeta中定义资源名、命名空间以及标签
		ObjectMeta: metav1.ObjectMeta{
			Name:      data.Name,
			Namespace: data.Namespace,
			Labels:    data.Label,
		},
		//Spec中定义类型，端口，选择器
		Spec: corev1.ServiceSpec{
			Type: corev1.ServiceType(data.Type),
			Ports: []corev1.ServicePort{
				{
					Name:     "http",
					Port:     data.Port,
					Protocol: "TCP",
					TargetPort: intstr.IntOrString{
						Type:   0,
						IntVal: data.ContainerPort,
					},
				},
			},
			Selector: data.Label,
		},
	}
	//默认ClusterIP,这里是判断NodePort,添加配置
	if data.NodePort != 0 && data.Type == "NodePort" {
		service.Spec.Ports[0].NodePort = data.NodePort
	}
	//创建Service
	_, err = K8s.ClientSet.CoreV1().Services(data.Namespace).Create(context.TODO(), service, metav1.CreateOptions{})
	if err != nil {
		logger.Error(errors.New("创建Service失败, " + err.Error()))
		return errors.New("创建Service失败, " + err.Error())
	}
	return nil
}

// 删除service
func (d *k8s_service) DeleteService(serviceName, namespace string) (err error) {
	err = K8s.ClientSet.CoreV1().Services(namespace).Delete(context.TODO(),
		serviceName, metav1.DeleteOptions{})
	if err != nil {
		logger.Error(errors.New("删除service失败, " + err.Error()))
		return errors.New("删除service失败, " + err.Error())
	}

	return nil
}

// 更新service
func (d *k8s_service) UpdateService(namespace, content string) (err error) {
	var service = &corev1.Service{}
	err = json.Unmarshal([]byte(content), service)
	if err != nil {
		logger.Error(errors.New("反序列化失败, " + err.Error()))
		return errors.New("反序列化失败, " + err.Error())
	}
	_, err = K8s.ClientSet.CoreV1().Services(namespace).Update(context.TODO(),
		service, metav1.UpdateOptions{})
	if err != nil {
		logger.Error(errors.New("更新service失败, " + err.Error()))
		return errors.New("更新service失败, " + err.Error())
	}
	return nil
}

// 获取每个namespace的service数量
func (d *k8s_service) GetServiceNumPerNp() (serviceNps []*K8s_serviceNp, err error) {
	namespaceList, err := K8s.ClientSet.CoreV1().Namespaces().List(context.TODO(),
		metav1.ListOptions{})
	if err != nil {
		return nil, err
	}
	for _, namespace := range namespaceList.Items {
		serviceList, err :=
			K8s.ClientSet.CoreV1().Services(namespace.Name).List(context.TODO(),
				metav1.ListOptions{})
		if err != nil {
			return nil, err
		}
		serviceNp := &K8s_serviceNp{
			Namespace: namespace.Name,
			DaemonNum: len(serviceList.Items),
		}
		serviceNps = append(serviceNps, serviceNp)
	}
	return serviceNps, nil
}
